/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package snmpapplication.beans;

import snmpapplication.Main;
import snmpapplication.log.Severity;

/**
 * Class that maps an Internet IPv4 address.
 * @author APetcu
 */
public class Ip {

    // The actual address
    private String address;

    /** 
     * Default constructor which will initialize the address with localhost 
     * or 127.0.0.1
     */
    public Ip() {
        this.address = "127.0.0.1";
    }

    /**
     * Constructor which will initialize the address with the given argument only
     * if is a valid IPv4 address
     * @param address 
     */
    public Ip(String address) {
        if (isValidIp(address)) {
            this.address = address;
        }
    }

    /**
     * Method used for getting the IP address
     * @return 
     */
    public String getAddress() {
        return address;
    }

    /**
     * Method used for setting the IP address
     * @param address 
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Method used for checking if @param addr is a valid IP address
     * @param addr
     * @return 
     */
    public static boolean isValidIp(String addr) {

        // Split the String and get each component number
        String[] elements = addr.split("\\.");
        Integer[] intElements = null;

        // The number of elements of the address must be exactly 4 else it's not
        // considered to be a valid address.
        if (elements.length > 4 || elements.length < 4) {
            Main.log.log(new Severity(Severity.SEV_MED), "Inserted String not conform with standard IP");
            return false;
        }

        intElements = new Integer[elements.length];

        // for each component number check if it's an integer by trying to make
        // a conversion from String to Integer
        for (int i = 0; i < elements.length; i++) {

            try {
                intElements[i] = Integer.parseInt(elements[i]);
            } catch (NumberFormatException ex) {
                Main.log.log(new Severity(Severity.SEV_ERR), "NumberFormatException la schimbare din int in String:" + ex.getMessage());
                return false;
            }

            // check if the numbers are between 0 and 255
            if (intElements[i] > 255 || intElements[i] < 0) {
                Main.log.log(new Severity(Severity.SEV_MED), "Inserted numbers not conform with standard IP");
                return false;
            }
        }

        return true;
    }

    @Override
    public String toString() {

        return this.address;

    }
}
